package com.coffeeloversupportlibrary.coffeelover.mercury.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;


import com.coffeeloversupportlibrary.R;
import com.coffeeloversupportlibrary.coffeelover.mercury.classify.DetailedActivity;
import com.coffeeloversupportlibrary.coffeelover.mercury.entity.CoffeeBeanSearchList;
import com.coffeeloversupportlibrary.coffeelover.mercury.main.adapter.CategoryAdapter;
import com.coffeeloversupportlibrary.coffeelover.mercury.utils.HttpUtils;
import com.coffeeloversupportlibrary.coffeelover.mercury.utils.JsonUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author 盛守义
 * @createTime 2021/11/22 10:32
 * @projectName TurningCoffee
 * @className CategoryActivity.java
 * @description TODO
 */
public class CategoryFragment extends Fragment {
    private Activity activity;
    private View view;
    private Button btn_search;
    private TextView tv_category;
    private ListView lv_category;
    private EditText et_search;

    private String[] types;

    private HttpUtils httpUtils;
    private JsonUtils jsonUtils;
    private CoffeeBeanSearchList coffeeList;

    private CategoryAdapter adapter;


    public CategoryFragment(Activity activity) {
        this.activity=activity;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view =inflater.inflate(R.layout.category_fragment,container,false);

        findView();
        getData();
        return view;
    }

//    @Override
//    public void onCreate(@Nullable Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.category_fragment);
//
//        findView();
//        getData();
//
//    }

    void findView(){
        httpUtils = new HttpUtils();
        jsonUtils = new JsonUtils();
        coffeeList = new CoffeeBeanSearchList();

        CateOnClickListener listener = new CateOnClickListener();
        btn_search = view.findViewById(R.id.btn_catesearch);
        tv_category = view.findViewById(R.id.tv_category);
        lv_category = view.findViewById(R.id.lv_category);
        et_search = view.findViewById(R.id.edt);

        tv_category.setOnClickListener(listener);
        btn_search.setOnClickListener(listener);
        types = new String[4];

        lv_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(view.getContext(), DetailedActivity.class);
                intent.putExtra("coffeeInfo", (Serializable) coffeeList.getData().getItems().get(i));
                startActivity(intent);
            }
        });
    }


    class CateOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tv_category:
                    Intent intent1 = new Intent(activity, SelectPopupWindowActivity.class);
                    startActivityForResult(intent1, 1);
                    break;
                case R.id.btn_catesearch:
                    String came = et_search.getText().toString().trim();
                    String[] type = new String[4];
                    try {
                        getData(came, type);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    void getData() {
        //Call call = httpUtils.getGetCall("http://10.7.88.9:8003","/coffee/coffeeList");
        Call call = httpUtils.getCall("/coffee/coffeeList");

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "网络连接崩溃了，绝对绝对不是我们的错", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String res = response.body().string();
                Log.e("CateGory", "onResponse: "+res);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        coffeeList = jsonUtils.getCoffeeSearchList(res);
                        Log.e("c", res );
                        System.out.println(res);
                        adapter = new CategoryAdapter(coffeeList.getData().getItems(), activity.getBaseContext(), mListener);
                        lv_category.setAdapter(adapter);
                    }
                });
            }
        });
    }

    void getData(String name, String[] types) throws JSONException {
        JSONObject jsonObject = new JSONObject();
        if(name == null || name.equals("")){
            jsonObject.put("name", "");
        }else{
            jsonObject.put("name", name);
        }

        JSONArray jsonArray = new JSONArray();
        for(int i = 0; i < types.length; i++){
            if(types[i] == null || types[i].equals("")){
            }else{
                jsonArray.put(types[i]);
            }
        }

        jsonObject.put("types", jsonArray);
        Log.e("jsonObject", jsonObject.toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString());
        Call call = httpUtils.getCall(requestBody, "/coffee/selectCoffee");
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "网络连接崩溃了，绝对绝对不是我们的错", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String res = response.body().string();
                Log.e("res", res);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        coffeeList = jsonUtils.getCoffeeSearchList(res);
                        if(coffeeList.getData().getItems() != null){
                            adapter.setList(coffeeList.getData().getItems());
                        }
                    }
                });
            }
        });
    }

    private CategoryAdapter.CardOnClickListerner mListener = new CategoryAdapter.CardOnClickListerner() {
        @Override
        public void myOnClick(int position, View v) {
            Intent intent = new Intent(activity, DetailedActivity.class);
            intent.putExtra("coffeeInfo", (Serializable)coffeeList.getData().getItems().get(position));
            startActivity(intent);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == -1 && requestCode == 1){
            types = data.getStringArrayExtra("types");
            Log.e("resullt", "onActivityResult: "+types[0]+types[1]+types[2]+types[3]);
            try {
                getData("", types);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
